/*
 */
#include "global.h"

#include <avr/io.h>
#include <util/delay.h>

//defines go here

#include "xuart.h"
#include "xbuffer.h"

#define CMD_ONE 0x01
#define CMD_TWO 0x02

extern xBuffer uartRxBuf;
extern xBuffer uartTxBuf;

void invokeCommand(int);
void registersInit(void);
void testBlinking(void);

void CommandONE(void);
void CommandTWO(void);

int main()
{
    unsigned short bytesRead, bytesCount;
    //unsigned char i = 0;
    unsigned char c;

    uartInit(1200);
    registersInit();
    //testBlinking();

    for(;;){
        bytesCount = bufferGetCount(&uartTxBuf);
        PORTB = ~bytesCount;

        bytesRead = bufferRead(&uartRxBuf, &c, 1);
        if(bytesRead){
            switch (c){
                case CMD_ONE:
                    CommandONE();
                break;

                case CMD_TWO:
                    CommandTWO();
                break;

                default:
                break;
            }

        }
    }
    return 0;
}

void CommandONE(){
    unsigned short i = 0;
    unsigned short bytesWritten;
    for(i=0; i < 512; i++){
        do{
            bytesWritten = bufferWrite(&uartTxBuf, (unsigned char*) &i, sizeof(i) );
            //_delay_us(10);
        }while(bytesWritten != sizeof(i));
        uartStartTransmission();
    }
    return;
}

void CommandTWO(){
    unsigned short i = 0;
    unsigned short bytesWritten;
    for(i=512; i > 0; i--){
        do{
            bytesWritten = bufferWrite(&uartTxBuf, (unsigned char*) &i, sizeof(i) );
            //_delay_us(20);
        }while(bytesWritten != sizeof(i));
        uartStartTransmission();
    }
    return;
}

//u08 uartReceiveByte(u08* data);
/*
void invokeCommand (cmdCode){
    u08 arg1, answer;
    //get int1 here
    switch (cmdCode){

        case CMD_SHIFT_LEFT:
            while(!uartReceiveByte(&arg1));
            answer = arg1 << 1;
            PORTB = ~answer;
            uartAddToTxBuffer(answer);
            uartSendTxBuffer();
            //uartSendByte(answer);
        break;

        case CMD_SHIFT_RIGHT:
            while(!uartReceiveByte(&arg1));
            answer = arg1 >> 1;
            PORTB = ~answer;
            uartAddToTxBuffer(answer);
            uartSendTxBuffer();
            //uartSendByte(answer);
        break;

    }

    //get int2 here
    //add int1 and int2
    //send back the answer
}
*/

void registersInit(){
    //DDRB = (1<<PB0) | (1<<PB1);
    DDRB = 0xFF;
    PORTB = 0xFF;
}

void testBlinking(){
    for(;;){
        PORTB = 0x00;
        _delay_ms(500);
        PORTB = 0xFF;
        _delay_ms(500);
    }
}
